package com.heima.behavior.advice;

import com.heima.behavior.dto.BehaviorDto;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;


@Component  //交给ioc
@Aspect  //切面
public class BehaviorAdvice {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Around("execution(* com.heima.behavior.service.impl.*.*(..))")   //环绕通知  解释  任意的返回值com.heima.behavior.service.impl 的类的方法的全部参数
    public Object saveBehaviorToRedis(ProceedingJoinPoint pjp){  //ProceedingJoinPoint正在运行的连接点
        //方法签名
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        if (methodName.startsWith("save")) {  //判断那个方法是save靠头的
            Object[] args = pjp.getArgs();
            BehaviorDto dto = (BehaviorDto) args[0];
            if (dto.getOperation() == 0) {  //getOperation     判断当前是曲线收藏还是 收藏
                // 操作类型 0  关注 点赞 不喜欢 收藏    1 取消关注 取消点赞 取消不喜欢 取消收藏
                //redis中的key包含了“行为+用户id+设备id+文章id”    //这里需要用户id dto.getUserId() ,所以在Controller的方法中已经赋值
                redisTemplate.boundValueOps(methodName + "_" + dto.getUserId() + "_" + dto.getEquipmentId() + "_" + dto.getArticleId()).set("");
            } else {
                redisTemplate.delete(methodName + "_" + dto.getUserId() + "_" + dto.getEquipmentId() + "_" + dto.getArticleId());
            }

        }
        try {
            return pjp.proceed();  //执行原方法
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

}

